<template>
  <view>
    <view >

      <view @click="goBack" class="back-style" >
        <u-icon name="arrow-left" size="40rpx" label="返回" color="#fff" labelColor="#fff" labelSize="36rpx"/>
      </view>

      <!--  视频   -->
      <swiper :style="'width: '+ windowWidth +'px; height: '+ windowHeight*0.9 +'px; background-color: #000000;'"
              :vertical="true" @animationfinish="animationfinish" @change="change" :current="current"
              :indicator-dots="false">
        <swiper-item v-for="(item,index) in dataList" :key="index">
          <view v-if="k==index" style="width: 100%;height: 100%">
            <!-- muted: 静音播放 h5浏览器默认自动播放得静音，以免影响用户体验。所以静音状态下就可以自动播放 -->
            <video v-if="isShowVideo" :id="item.id" :muted="item.isPlay" :autoplay="true"
                   :webkit-playsinline="true" :x-webkit-airplay="true" :playsinlin="true"
                   :enable-play-gesture="true" :enable-auto-rotation="true" :show-screen-lock-button="true"
                   :controls="true" :show-center-play-btn="false" play-btn-position="bottom" :http-cache="true"
                   :custom-cache="true" :show-play-btn="true" :show-fullscreen-btn="true" :show-loading="true"
                   :enable-progress-gesture="true" :src="item.mp4_url" @controlstoggle="ctrlToggle"
                   :style="'width: 100%; height: 100%; background-color: #000000;'" object-fit="cover"
                   :poster="tvInfo.tv_image|handlePic" @play="videoPlay(item.state,$event)" @ended="ended"
                   class="video-box" @progress="progress" @pause="videoPause" >
            </video>

            <view v-if="!isShowVideo" @click="clickTvImage(currentEpisode)" style="width: 100%; height: 100%;">
              <image :src="tvInfo.tv_image|handlePic" mode="aspectFit"
                     :style="'width: 100%; height: 100%; background-color: #000000;'" />
            </view>

            <view class="userInfo" >
              <!-- 2.点赞 -->
              <view @click="clickLike();" class="icon_box">
                <image :src="currentEpisode.isLike?'/static/images/xin.png':'/static/images/xin-2.png'" class="icon_img"/>
                <view class="tn-text-sm tn-color-white" :class="{'dm-main-text-color':currentEpisode.isLike}">
                  {{currentEpisode.like_num>-1?currentEpisode.like_num:0}}
                </view>
              </view>
              <!-- 3.追剧 -->
              <view @click="clickFollowTv" class="icon_box">
                <image :src="isFollowTv?'/static/images/zhuiju.png':'/static/images/zhuiju-2.png'" class="icon_img"/>
                <text class="tn-text-sm tn-color-white">追剧</text>
              </view>

              <view @click="clickShare" class="icon_box">
                <image src="@/static/images/wx.png" class="icon_img"/>
                <text class="tn-text-sm tn-color-white">分享</text>
              </view>

              <!-- 4.分享 -->
<!--              <view style="opacity: 0.9; margin-top: 40rpx;">-->
<!--                <view style="opacity: 0;">-->
<!--                  <u-button openType="share" text="分享"></u-button>-->
<!--                </view>-->
<!--                <view style="display: flex;flex-direction: column;align-items: center;margin-top: -90rpx;">-->
<!--                  <image src="@/static/images/wx.png" class="icon_img"/>-->
<!--                  <text class="tn-text-sm tn-color-white">分享</text>-->
<!--                </view>-->
<!--              </view>-->
            </view>

          </view>
        </swiper-item>
      </swiper>

      <view class="bottom-container">
        <!-- 最底下的文字部分 -->
        <view class="choseContent" >
          <view class="choseSeries" @click="xuanji()" v-if="dataList[k]">
            <view>{{dataList[k].tv_name}}·<span v-if="totalEpisode">全{{ totalEpisode }}集·第 {{dataList[k].series}} 集</span> <u-icon class="tn-margin-left" name="arrow-up" size="30rpx" color="#fff" labelColor="#fff" /></view>
          </view>
        </view>
        <!-- 倍速控制     -->
        <view class="speed-ctrl">
          <view class="speed-icon" @click="toggleSpeedOptions" >
            <text class="icon">倍数{{currentSpeed}}x</text>
          </view>
          <!-- 遮罩层，控制点击空白关闭 -->
          <view v-if="showSpeedOptions" class="overlay" @click="toggleSpeedOptions"></view>
          <!-- 弹出的倍速选项框 -->
          <view class="speed-options" v-show="showSpeedOptions">
            <view v-for="speed in speedList" class="option" @click="setSpeed(speed)">{{speed}}x</view>
          </view>
        </view>
      </view>




      <!-- 短剧选集弹窗开始 -->
      <tn-popup  v-model="showXuanjiPopup" @close="closeXuanjiPopup" @open="openXuanjiPopup" :border-radius="40" mode="bottom" length="60%">
        <view class="tn-padding-xl tn-flex tn-flex-direction-row tn-flex-col-center " style="background-color: #242424;">
          <view class="tn-text-bold tn-color-white tn-text-lg tn-margin-right">{{ tvInfo.tv_name }}</view>
          <tn-tag backgroundColor="#F9B6B6" fontColor="#FB4378" shape="radius" size="sm">更新至 {{ totalEpisode }} 集</tn-tag>
        </view>
        <view class="tn-bg-black" style="height: 100%">
          <view class="tn-padding tn-flex tn-flex-direction-row ">
            <view v-for="(item,index) in episodeRangeTabs" @click="clickEpisodeTab(item,index)" >
              <view :class="currentTabIdx===index?'dm-main-text-color tn-text-bold':'tn-color-white'" >
                {{item.name}}  <text class="tn-icon-title" v-if="index!=episodeRangeTabs.length-1"/>
              </view>
            </view>
          </view>
          <view>
<!--            <view class="tn-text-lg tn-color-red">{{series_interval}}</view>-->

            <u-grid align="left" :col="6" :border="false">
              <u-grid-item  v-for="n in series_interval" :key="n" bg-color="transparent" :custom-style="{padding:'5px 0'}">
                <!-- #ifdef H5 -->
                <!--   n 从1开始             -->
                <view class="tn-radius tn-flex tn-flex-col-center tn-flex-row-center episode-box" :style="currentEpisode.series==(30*currentTabIdx+n)?'background-color: #FB4378':'background-color: #737373'"  @click="chooseEpisode(30*currentTabIdx+n)" >
                  <view>{{30*currentTabIdx+n}}</view>
                  <view class="lock-box" v-if="!dataList[30*currentTabIdx+(n-1)].hadPay"><text class="tn-icon-lock tn-color-white tn-text-xs"/></view>
                </view>
                <!-- #endif -->
                <!-- #ifdef MP-WEIXIN -->
                <!--   n 从0开始             -->
                <view class="tn-radius tn-flex tn-flex-col-center tn-flex-row-center episode-box" :style="currentEpisode.series==(30*currentTabIdx+n+1)?'background-color: #FB4378':'background-color: #737373'"   @click="chooseEpisode(30*currentTabIdx+n+1)" >
                  <view>{{30*currentTabIdx+n+1}}</view>
                  <view class="lock-box" v-if="!dataList[30*currentTabIdx+n].hadPay"><text class="tn-icon-lock tn-color-white tn-text-xs"/></view>
                </view>
                <!-- #endif -->
              </u-grid-item>
            </u-grid>
          </view>
        </view>
      </tn-popup>
      <!-- 短剧选集弹窗结束 -->

      <!-- 充值弹窗开始 -->
      <tn-popup  v-model="rechargeShow" @close="rechargeShow = false" @open="rechargeOpen" :border-radius="40" mode="bottom">
        <view class="tn-padding-sm " style="background-color: #242424;border-top-left-radius: 20px;border-top-right-radius: 20px">
          <view class="tn-flex tn-flex-direction-row tn-flex-col-center " >
            <view class="tn-text-bold tn-color-white tn-text-lg tn-margin-right">解锁剧集</view>
            <!-- <view class="dm-button-sm" @click="doUnlockTv" style="background: linear-gradient(276deg, #FA3A68 7%, #FF81D9 93%);">全集卡解锁</view> -->
            <view class="dm-margin-left-right-xs"/>
            <!-- <view class="dm-button-sm" @click="showRewardedVideoAd" style="background: linear-gradient(276deg, #FA3A68 7%, #FF81D9 93%);">广告解锁</view> -->
          </view>
          <view class="tn-flex tn-flex-direction-row tn-flex-col-center tn-color-white tn-text-sm tn-flex-row-between tn-margin-top-sm">
            <view>本集解锁：{{ currentEpisode.pay }}金豆</view>
            <view>全集解锁卡：{{vuex_user.unlock_tv_card || 0}}张</view>
            <view>账户余额：{{ balanceTotal }}金豆</view>
          </view>
        </view>
        <view class="tn-bg-black">
          <scroll-view :scroll-top="0" scroll-y="true" class="scroll-Y"  @scroll="scroll" @touchmove.stop>
            <recharge-list @rechargesuccess="reloadTotalBalance" :tv-name="this.tvInfo.tv_name" :vip-recharge-list="vipRechargeList" :bean-recharge-list="beanRechargeList"/>
            <u-gap :height="50"/>
          </scroll-view>
        </view>
      </tn-popup>
      <!-- 充值弹窗结束 -->

      <!-- 分享二维码弹窗开始 -->
      <tn-popup  v-model="showSharePopup" mode="center">
        <view class="popup-content">
          <text>微信扫一扫观看</text>
          <view class="qrcode-canvas">
            <l-painter css="width: 160px; height: 160px;" ref="painter1" performance>
              <l-painter-view css="padding:5px;position:absolute;">
                <l-painter-qrcode
                  css="background:#fff;width: 130px; height: 130px;padding:10px;border-radius: 10rpx;"
                  :text="shareUrl" />
              </l-painter-view>
            </l-painter>
          </view>
        </view>
      </tn-popup>
      <!-- 分享二维码弹窗结束 -->
    </view>

  </view>
</template>

<script>
import Config from "../../utils/config";

var that; // 当前页面对象
let rewardedVideoAd = null; //激励广告
let interstitialAd = null; //插屏广告

import RechargeList from "@/components/recharge-list/recharge-list.vue";
import common_mixin from '@/libs/mixin/common_mixin.js'
import {getStorageSync, hideLoading, showLoading, toast} from "../../utils/utils";
import UPopup from "../../uni_modules/uview-ui/components/u-popup/u-popup.vue";
import UGap from "../../uni_modules/uview-ui/components/u-gap/u-gap.vue";
import BannerAd from "../../components/banner-ad/banner-ad.vue";
import {clickLike, getShareTvUrl} from "../../api/api";
import store from "../../store";
import TnPopup from "../../uni_modules/tuniao-ui/components/tn-popup/tn-popup.vue";

export default {
  mixins: [common_mixin],
  components: {
    TnPopup,
    BannerAd,
    UGap,
    UPopup,
    RechargeList,
  },
  data() {
    return {
      adviseMore: false, //默认不展示推荐弹窗，一部剧最后一集播完才提示
      vipRechargeList: [], //充值套餐列表
      beanRechargeList: [], //充值套餐列表
      isShowVideo: false, //视频播放组件是否展示
      isFollowTv: false,
      rechargeShow: false, //充值套餐弹窗

      // 选集框
      showXuanjiPopup: false,
      totalEpisode: 0,
      episodeRangeTabs: [],
      currentTabIdx: 0,
      currentTab: {},
      series_start: 1,
      series_end: 30,
      series_interval: 0,

      windowWidth: 0,
      windowHeight: 0, //swiper组件高度

      dataList: [],
      k: 999, // 当前播放的索引
      current: 999, //和k值一起改，模板的值为0 ，但是为0时进来不会自动播放，所以改成3，也可以改成其他数字
      currentEpisode: {},

      balanceTotal: 0, //金豆总计：余额+赠送
      all: [],
      tvInfo: {
        tv_name: "",
        tv_image: "",
        tv_id: ""
      }, //包含电视剧名称，封面图和ID
      jumpEpisode:1,

      hideIcon: false,// 隐藏所有图标
      //广告
      isPlaying: false, // 控制间隔几集播放激励广告的
      watchingList: new Set([]),// 观看了的剧集，收集不重复的剧集
      isAllowShowRewardedAd: false,
      isWatchingRewardedAd:false,// 是否在看激励广告

      speedList:['0.5','1.0','1.5','2.0'],
      showSpeedOptions: false,
      currentSpeed: '1.0',
      showSharePopup:false,
      shareUrl:'',

      refreshTimer:null // 更新剧的定时

    }
  },
  watch: {
    async k(k, old_k) {
      console.log("剧集变动...k=", k, "old_k=", old_k,"tvinfo=",this.tvInfo);
      this.isShowVideo = false
      //把当前视频信息存到currentInfo
      this.currentEpisode = this.dataList[k];
      this.collectWatchingAndShowRewardedVideoAd();
      this.checkAndPayEpisode()
      this.recordHistory()
      this.checkLike()
    },
    async isShowVideo(v,old_v) {
      if (v) {
        setTimeout(()=>{
          this.setSpeed(this.currentSpeed);
          // 需要等video渲染完才能设置
        },500);
      }
    }
  },
  beforeDestroy() {
    console.log('player销毁');
    if(this.refreshTimer) {
      console.log('清除定时器')
      clearTimeout(this.refreshTimer);
    }
  },
  async onLoad(option) {
    this.windowWidth = uni.getSystemInfoSync().windowWidth
    this.windowHeight = uni.getSystemInfoSync().windowHeight;
    this.tvInfo.tv_id=option.tvId
    this.jumpEpisode=option.episode
    console.log("当前剧id:"+this.tvInfo.tv_id)
    await this.loadAllEpisode(this.tvInfo.tv_id,this.jumpEpisode)

  },
  async onShow() {
    console.log('onshow')
    this.tvInfo = await this.getVideoDetail(this.tvInfo.tv_id)
    this.totalEpisode = this.tvInfo.all_series
    //计算总集数并分组
    this.computer()
    this.checkFollow()

    this.loadInterstitialAd();
    this.loadRewardedAd();
    this.getRechargeList()
    this.reloadTotalBalance();
    this.enableRefreshMp4UrlTimer();

    setTimeout(() => {
      if (this.dataList.length == 0) {
        this.isShowVideo = false;
        return;
      }
    }, 2000)

    console.log("this.k.pay=", this.dataList[this.k]);
    if (!this.dataList[this.k]) {
      console.log('退出了...');
      return;
    }
    this.checkAndPayEpisode()


  },
  onUnload() {
    // this.recordHistory()
  },
  onHide() {
    // this.recordHistory()
  },
  methods: {
    onShareAppMessage(res) {
      console.log('分享', res);
      return {
        title: Config.appName, // 默认为小程序名称
        path: '/pages_sub/player/player?tvId='+this.tvInfo.tv_id+"&episode="+this.currentEpisode.series,
        imageUrl: this.tvInfo.tv_image, // 默认为当前页面的截图
        success: (res) => {
          // 转发成功
          console.log('转发成功:', res);
        },
        fail: function(res) {
          console.log('转发失败:', res);
        },
      }
    },
    // 切换倍速弹框的显示状态
    toggleSpeedOptions() {
      this.showSpeedOptions = !this.showSpeedOptions;
    },
    setSpeed(rate) {
      // 获取 video 元素
      console.log('设置'+rate+'倍速 ；id: '+ this.currentEpisode.id)
      this.showSpeedOptions=false;
      this.currentSpeed=rate
      let videoContext = uni.createVideoContext(this.currentEpisode.id, this)//这里的'myVideo'要和上方video标签的id相对应
      videoContext.playbackRate(parseFloat(rate));
    },
    ////////////////////////////////////////////////////////////////////////////////////////  广告相关

    //加载插屏广告
    loadInterstitialAd() {
      console.log("插屏广告", this.adConfig.wx_interstitial_stopplayer)
      let config = this.adConfig.wx_interstitial_stopplayer;
      if (wx.createInterstitialAd && config) {
        interstitialAd = wx.createInterstitialAd({
          adUnitId: config.provider_ad_id
        })
        interstitialAd.onLoad(() => {
          console.log('插屏广告加载成功')
        })
        interstitialAd.onError((err) => {
          console.log('插屏广告加载失败', err)
        })
        interstitialAd.onClose(() => {

        })
      }
    },
    //显示插屏广告
    showInterstitialAd() {
      console.log("显示插屏", interstitialAd)
      if (interstitialAd) {
        // 重新拉取新广告
        interstitialAd.load()
          .then(() => {
            // 显示插屏广告，捕捉错误
            interstitialAd.show().catch(() => {
              // 失败重试
              interstitialAd.load()
                .then(interstitialAd.show())
                .catch(err => {
                  console.log('插屏广告显示失败')
                })
            })
          })
          .catch(err => {
            console.log('插屏广告拉取失败', err)
          })
      }
    },
    //加载激励广告
    async loadRewardedAd() {
      let config = this.adConfig.wx_reward_player;
      if (!config) {
        return;
      }
      let data = await this.$api.adTimesLimit({ad_id: config.ad_id});
      if (data.code==101) {
        this.isAllowShowRewardedAd = false;
        return;
      }
      this.isAllowShowRewardedAd = true;
      if (wx.createRewardedVideoAd) {
        rewardedVideoAd = wx.createRewardedVideoAd({
          adUnitId: config.provider_ad_id
        })
        rewardedVideoAd.onLoad(() => {
          console.log('激励广告加载成功')
        })
        rewardedVideoAd.onError((err) => {
          console.log('激励广告加载失败', err)
        })
        rewardedVideoAd.onClose((res) => {
          this.isWatchingRewardedAd=false
          // 用户点击了【关闭广告】按钮
          if (res && res.isEnded) {
            console.log("播放结束，可发放奖励");
            this.look_ads_end()
          } else {
            this.look_ads_end()
            console.log("中途结束");
          }
          this.checkAndPayEpisode()
        })
      }
    },
    //显示激励广告
    async showRewardedVideoAd() { // 显示激励视频
      console.log("开始激励视频")
      let config = this.adConfig.wx_reward_player;
      if (!config || !this.isAllowShowRewardedAd) {
        return;
      }
      let data = await this.$api.adTimesLimit({ad_id: config.ad_id});
      if (data && data.code==101) {
        console.log("错误：", data.msg)
        this.isAllowShowRewardedAd = false
        return;
      }
      if (rewardedVideoAd) {
        console.log("开始加载激励视频和显示")
        this.isWatchingRewardedAd=true
        rewardedVideoAd.load()
          .then(() => {
            rewardedVideoAd.show().catch(() => {
              // 失败重试
              rewardedVideoAd.load()
                .then(() => rewardedVideoAd.show())
                .catch(err => {
                  that.rechargeOrAd();
                  console.log('激励视频 广告显示失败')
                })
            })
          })
          .catch(err => {
            that.rechargeOrAd();
            console.log('激励视频 广告拉取失败', err)
          })
      }
    },
    // 间隔几集播放视频
    collectWatchingAndShowRewardedVideoAd() {
      console.log("collect watching:",this.dataList[this.k].series,this.watchingList)
      let config = this.adConfig.wx_reward_player;
      if (!config || !this.isAllowShowRewardedAd) {
        return;
      }
      this.watchingList.add(this.dataList[this.k].series)
      console.log(this.watchingList)
      if (this.watchingList.size >= config.interval_series) {
        console.log("间隔了" + this.watchingList.size + "集,开始播放广告")
        this.watchingList = new Set([]);
        this.showRewardedVideoAd();
      }
    },
    //用户看完激励广告
    async look_ads_end() {
      let config = this.adConfig.wx_reward_player
      console.log(config)
      await this.$api.adJiangLi({ad_id:config.ad_id})
      toast('奖励已发送')
      this.balanceTotal+=this.adConfig.wx_reward_player.reward_beans
      let userinfo = await this.reloadUserInfo();
      store.commit('$tStore', {
        name: 'vuex_user',
        value: userinfo
      });
    },
    showAdReward() {
      console.log("显示广告")
      if (this._isLoaded) {
        console.log("广告已经加载完了")
        this._rewardedVideoAd.show()
      }
    },
    //----------------------------------------------------------------  广告

    async getRechargeList() {
      let data = await this.$api.getRechargeList({});
      this.vipRechargeList = data.vipRechargeList
      this.beanRechargeList = data.beanRechargeList
    },
    ctrlToggle(e) {
      console.log("进度条显示状态------", e.detail.show);
      this.hideIcon = !e.detail.show;

    },
    enableRefreshMp4UrlTimer() {
      console.log('开启刷新链接的定时');

      // 如果定时器已经存在，先清除
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
      }

      // 设置一个新的定时器
      let time = 1000 * 60 * 10; // 10分钟
      this.refreshTimer = setInterval(() => {
        this.refreshMp4Url(); // 刷新链接
      }, time);
    },
    // 用户有可能一直连续看，到一定剧集地址过期了，需要定时刷新url
    async refreshMp4Url () {
      let params = {
        jump_series: this.currentEpisode.series, //如果参数里有集数，则传集数，没集数默认空
        tv_id: this.tvInfo.tv_id,
      };
      let data = await this.$api.getAllEpisode(params);
      const newList = data.seriesList;
      for(let i = 0; i < newList.length; i++) {
        for(let j = 0; j < this.dataList.length; j++) {
          if(newList[i].series == this.dataList[j].series && this.dataList[j].series!=this.currentEpisode.series) { // 当时的集已经在播放了就不需要替换
            this.dataList[j].mp4_url = newList[i].mp4_url;
          }
        }
      }

    },
    async loadAllEpisode(tvId, episode) {
      let params = {
        jump_series: episode, //如果参数里有集数，则传集数，没集数默认空
        tv_id: tvId,
      };
      let data = await this.$api.getAllEpisode(params)
      console.log("处理后的数据", data);
      this.jumpEpisode = data.jump_series
      this.current = this.jumpEpisode-1
      this.k = this.jumpEpisode-1
      console.log("跳转到第"+this.jumpEpisode+"集")

      this.dataList = data.seriesList
    },
    //点击选集图标
    xuanji() {
      this.setTab();
      this.showXuanjiPopup = true
    },
    setTab () {
      this.currentTab=this.episodeRangeTabs[this.currentTabIdx];
      this.series_start=this.currentTab.start
      this.series_end=this.currentTab.end
      this.series_interval = this.series_end-this.series_start+1
    },
    //点击弹出框的分集tab
    clickEpisodeTab(item,index) {
      console.log('clickitem', item);
      this.currentTabIdx = index;
      this.setTab();
    },
    //点击选集跳转
    chooseEpisode(episode) {
      this.showXuanjiPopup=false
      // watch监听了k的变化，这里里会出现没有变化的，需要再进行付费检查
      let toVideoIdx = episode-1; // datalist 是全部集数的信息，剧集-1 就是要观看集的索引
      if (this.k==toVideoIdx) {
        this.checkAndPayEpisode()
      }
      // 有变化直接由watch那里触发付费检查
      this.current = toVideoIdx;
      this.k = toVideoIdx;
    },
    async payEpisode(item, index) {
      if (item.pay == 0 || item.hadPay) {
        return false;
      }
      let params = {
        tv_id: this.tvInfo.tv_id,
        tv_name: this.tvInfo.tv_name,
        series: item.series,
        pay_amount: item.pay,
        series_id: item.id
      };
      let res = await this.$api.payEpisodeByBean(params)
      let userinfo = await this.reloadUserInfo();
      store.commit('$tStore', {
        name: 'vuex_user',
        value: userinfo
      })
      if (res && res.code==102) { // 余额不足
        this.rechargeOrAd(); //充值或看广告解锁
        toast(res.msg)
        return false;
      }
      toast('自动购买成功！该集已解锁');

      //遍历dataList数组，找到付费的集数，并解锁，防止用户来回切换标签页后导致未解锁
      for (var i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].id == item.id) {
          this.dataList[i].hadPay = true
        }
      }
      return true;
    },
    //全集解锁
    async unlockTv() {
      let params = {
        tv_id: this.tvInfo.tv_id,
        tv_name: this.tvInfo.tv_name
      };
      let res = await this.$api.unlockTv(params)
      let userinfo = await this.reloadUserInfo();
      store.commit('$tStore', {
        name: 'vuex_user',
        value: userinfo
      })
      if (res && res.code==105) { // 卡不足
        this.rechargeOrAd(); //充值或看广告解锁
        toast(res.msg)
        return false;
      }
      toast('全集解锁成功！该集已解锁');
      //遍历dataList数组解锁
      for (var i = 0; i < this.dataList.length; i++) {
        this.dataList[i].hadPay = true
      }
    },
    //计算一共有多少组数据
    async computer() {
      let numTabs = Math.ceil(this.totalEpisode / 30);
      for (var i = 0; i < numTabs; i++) {
        let start = i * 30 + 1;
        let end = Math.min(start + 29, this.totalEpisode);

        this.episodeRangeTabs.push({
          name: start + "-" + end,
          start: start,
          end: end
        });
      }
    },
    ended() {
      if (this.k == this.dataList.length - 1) {
        uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).seek(0)
        uni.createVideoContext(this.dataList[this.k]._id + '' + this.k, this).pause()
        this.adviseMore = true; //全部播放完后，推荐更多视频
      } else {
        this.current = this.k + 1
      }
    },
    async clickShare() {
      let params ={
        tv_id:this.tvInfo.tv_id,
        series:this.currentEpisode.series
      }
      let res =await this.$api.getShareTvUrl(params);
      this.shareUrl = res;
      console.log('shareUrl:'+this.shareUrl);
      this.showSharePopup=true;
    },
    async clickFollowTv() {
      let params ={
        tv_id:this.tvInfo.tv_id,
        isFollow:true
      }
      if(this.isFollowTv) {
        let res = await this.$api.cancelFollowTv(params);
        toast('取消追剧')
        this.isFollowTv=false
        return
      }
      console.log("点击追剧");
      let res = await this.$api.followTv(params);
      toast('追剧成功')
      this.isFollowTv=true
    },

    //点击播放&&暂停
    videoPlay(state, event) {
      this.isPlaying = true
      console.log("点击了播放", event);
    },
    //视频暂停
    videoPause(event) {
      console.log("点击了暂停", event)
      if (!this.isPlaying) { // 已经暂停过了 播放和停止会被连续触发两次
        return;
      }

      this.isPlaying = false
      if (interstitialAd && this.isShowVideo) {
        this.showInterstitialAd()
      }
    },
    //当视频暂停时，会展示封面图，点击封面图触发此事件
    async clickTvImage(item) {
      console.log("点击了封面图");
      this.checkAndPayEpisode()
    },
    change(event) {
      this.k = event.detail.current;
      //current一定要改，否则会出现选集黑屏的问题
      this.current = event.detail.current
    },
    //swiper动画结束时会触发animationfinish事件
    animationfinish(event) {
      //这里进行判断，如果是最后一个视频就加载视频进入列表
      if (this.k == this.dataList.length - 1) {
        // this.GETNEW()
      }
    },
   async checkLike () {
      let episodeId = this.dataList[this.k].id;
      let params= {
        series_id:episodeId,
      };
      let data = await this.$api.checkLike(params)
      this.dataList[this.k].isLike = data.isLike
    },
    async checkFollow () {
      let params = {
        tv_id:this.tvInfo.tv_id,
      };
      let data = await this.$api.checkFollow(params)
      this.isFollowTv = data.isFollow
    },
    //用户点赞操作
    async clickLike() {
      this.dataList[this.k].isLike = !this.dataList[this.k].isLike
      const video = this.dataList[this.k];
      let episodeId = this.dataList[this.k].id;
      let params =  {
        series_id:episodeId,
      };
      if (this.dataList[this.k].isLike) {
        video.like_num = video.like_num * 1 + 1
        await this.$api.clickLike(params)
      } else {
        video.like_num = video.like_num * 1 - 1
        await this.$api.removeLike(params)
      }

    },

    //记录用户的看剧记录
    recordHistory() {
      console.log("记录下观看记录")
      if (!this.currentEpisode) {
        return
      }
      let params = {
        series_id: this.currentEpisode.id,
      }
      this.$api.recordHistory(params);
    },

    //计算金豆余额
    reloadTotalBalance() {
      this.balanceTotal = this.getTotalBalance();
    },
    openXuanjiPopup() {
      this.showXuanjiPopup = true
    },
    closeXuanjiPopup() {
      this.showXuanjiPopup = false
      this.isShowVideo = !this.isNeedPay(this.dataList[this.k])
    },
    rechargeOpen() {
      console.log("充值弹窗开启");
      if (this.vipRechargeList.length>0 && this.beanRechargeList.length>0) {
        return
      }
      this.getRechargeList();
    },
    upper: function(e) {

    },
    lower: function(e) {

    },
    scroll: function(e) {
    },
    //视频加载进度
    progress(e) {
      // console.log("当前视频加载进度=", e.detail.buffered);
    },
    progress2(e) {
      // console.log("预加载视频进度=", e.detail.buffered);
    },

    //选择了解锁卡解锁
    async doUnlockTv() {
      const item = this.dataList[this.k]
      if (item.price == 0 ) {
        return;
      }
      let unlockTvCard = this.vuex_user.unlock_tv_card;
      console.log("解锁卡："+unlockTvCard)
      if (!unlockTvCard) {
        toast('你还没有全集解锁卡');
        return;
      }
      let res =  await this.unlockTv(item, this.k);
      if (res) {
        this.showVideo();
      }
    },
    showVideo() {
      this.showXuanjiPopup=false
      //延迟0.5秒，用户观感更顺滑
      setTimeout(() => {
        console.log("开始播放视频")
        this.isShowVideo = true;
      }, 500)
    },
    // 检查并支付剧集
    checkAndPayEpisode () {
      if (this.isNeedPay(this.dataList[this.k])) {
        this.rechargeOrAd(); //充值或看广告解锁
        return;
      }
      this.showVideo()//展示视频播放组件
    },
    // 判断是否需要支付
    isNeedPay (item) {
	  let userInfo = uni.getStorageSync("userInfo");
	  let plus_type = userInfo?userInfo.plus_type:0;
	  if(plus_type==1){
		this.rechargeShow = false;
		return false;
	  }
      return item.pay > 0 && item.hadPay == false
    },
    //拉起充值或看广告解锁剧集 如果判断需要支付后直接调用这个方法
    rechargeOrAd() {
      this.isShowVideo = false; //关闭视频播放组件
      this.reloadTotalBalance();
      // 如果有余额自动解锁
      if (this.balanceTotal>=this.dataList[this.k].pay) {
        this.payByJinDouAndShowVideo()
        return;
      }
      // 全集卡解锁或者广告
      this.rechargeShow = true;
    },
    //选择了金豆解锁
    async payByJinDouAndShowVideo() {
      console.log('点击金豆解锁------------------',this.k);
      let res = await this.payEpisode(this.dataList[this.k], this.k);
      if (res) {
        this.showVideo();
      }
    },
    //用户看完激励广告
    async rewardAdsFinish() {
      let params = {
        adpId: this.rewardAdpId, //广告位ID
        episode: this.dataList[this.k].episode,
        tv_id: this.tvInfo.tv_id,
      }
      let data = await this.$api.adRewardedUnlockEpisode(params)
      if (data.unlockEpisodeIds && data.unlockEpisodeIds.length > 0) {
        for (var i = 0; i < that.dataList.length; i++) {
          if (data.unlockEpisodeIds.includes(that.dataList[i]._id)) {
            that.dataList[i].hadPay = true
          }
        }
        toast('剧集已解锁');
        that.showVideo();
      }
    }
  }
}
</script>


<style>
page {
  background-color: #000000;
}
.bottom-container{
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding: 0 5px;
  position: absolute;
  bottom: 15px;
  width: 100%;
  z-index: 99;
}
// 倍速
.speed-ctrl {
  flex-direction: column;
  align-items: flex-end;
  position: relative;
  margin-left: 5px;
}
.speed-icon {
  background-color: #2c2b2b;
  color: #fff;
  border-radius: 11px;
  height: 35px;
  width: 70px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 10;
}

.speed-options {
  position: absolute;
  bottom: 60px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 8px;
  overflow: hidden;
  z-index: 99;
}

.option {
  padding: 10px 20px;
  color: #fff;
  text-align: center;
  cursor: pointer;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.option:last-child {
  border-bottom: none;
}

.option:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.choseContent {
  flex-direction: column;
  justify-content: flex-start;
  color: #ffffff;
}
.choseSeries {
  background-color: #2c2b2b;
  padding: 7px 10px;
  border-radius: 22rpx;
}

.scroll-Y {
  height: 850rpx;
}

.back-style {
  margin-top: 60px;
  color: #FFFFFF;
  position: fixed;
  margin-left: 30rpx;
  z-index: 9999999;
  height: 60rpx;
  width: 150rpx;
}

.userInfo {
  z-index: 999;
  position: absolute;
  bottom: 110px;
  right: 10px;
  display: flex;
  flex-direction: column;
}
.icon_box {
  opacity: 0.9;
  margin-top: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.icon_img {
  width: 28px;
  height: 28px;
}

.tn-grid-item {
  background: none;
}
.bannerAdContainer {
  display: flex;
  width: 100%;
  position: absolute;
  bottom: 0;
  z-index: 9999999;
}

.episode-box {
  position:relative;
  background-color:#737373;
  height: 50px;
  width: 50px;
  color: #FFFFFF;
}
.lock-box {
  position: absolute;
  right: 2px;
  top: 2px;
}


/* 遮罩层 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
  background: transparent;
}
/* share popup */
.popup-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
.qrcode-canvas {
  //width: 200px;
  //height: 200px;
  //margin: 20px 0;
}

</style>
